package cn.xiaobai.config;

import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 定时器配置
 *
 * @Author yangdaji
 * @Date 2022/11/11 0011
 * @PackageName xiaobai.config
 * @ClassName ScheduleConfig
 */
@Component
public class ScheduleConfig {

    /**
     * 定时任务线程池，用于websocket客户端重连。
     *
     * @return
     */
    @Bean
    public ThreadPoolTaskScheduler getWebSocketThreadPoolTaskScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(5);
        threadPoolTaskScheduler.setRemoveOnCancelPolicy(true);
        //丢弃最早的任务（因为websocket组件中添加了定时重连机制，这里可以忽略部分重连线程）
        threadPoolTaskScheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        threadPoolTaskScheduler.setThreadNamePrefix("thread-task");
        threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskScheduler.setAwaitTerminationSeconds(10);
        threadPoolTaskScheduler.initialize();

        return threadPoolTaskScheduler;
    }

}
